package com.lcm.algorithm.datatest.search;

/**
 * @description: 二分查找
 * @author: lcm
 * @create: 2020-04-02 11:03
 **/

public class BinarySearch {

    public static void main(String[] args){
        int[] array=new int[]{1,2,3,4,5,6,7,8,9,10};
        System.out.println(binarySearch(array,5));
        System.out.println(binarySearch(array,10));
        System.out.println(binarySearch(array,30));
    }

    /**
     * 二分查找返回数组下标，无返回-1
     * 需要注意边界值，left和right设为数组的起始下标，
     * left<=right 因为相等也是一个数组,依然需要判断
     * @param array
     * @return
     */
    public static int binarySearch(int[] array,int target){
        int left=0,right=array.length-1;
        while(left<=right){
            int mid=(left+right)/2;
            if(array[mid]==target)
                return mid;
            if(array[mid]<target){
                left=mid+1;
            }else{
                right=mid-1;
            }
        }
        return -1;
    }

}
